﻿using System;
using System.Net.Mail;
using System.Text;

namespace Quizz.Infrastructure.Common
{
    /// <summary>
    /// Mail sender. Before use this, please add smtp config.
    /// </summary>
    public class MailSender
    {
        #region Vars

        private static bool _configurated;
        #endregion

        #region Constructor
        static MailSender()
        {
            Configure();
        }
        #endregion

        #region Properties

        /// <summary>
        /// Get Smtp Client Info
        /// </summary>
        public static SmtpClient SmtpClient { get; private set; }

        #endregion

        #region Methods

        /// <summary>
        /// Auto confige use configure file.
        /// If configure setting not exist, default value will be use.
        /// </summary>
        public static void Configure()
        {
            try
            {
                // Use settings in .config file
                SmtpClient = new SmtpClient();
                _configurated = true;
            }
            catch (Exception ex)
            {
                // Log here
                _configurated = false;
            }
        }

        /// <summary>
        /// Send an email to a address.
        /// </summary>
        /// <param name="toAddresses">Receive addresses</param>
        /// <param name="subject">Mail subject</param>
        /// <param name="body">Mail content</param>
        /// <param name="isHtml">Is send a html content ? Default : false</param>
        /// <returns></returns>
        public static void Send(string[] toAddresses, string subject, string body, bool isHtml = false)
        {
            if (!_configurated)
            {
                Configure();
            }

            var message = new MailMessage()
            {
                Subject = subject,
                Body = body,
                IsBodyHtml = isHtml
            };
            foreach (var mail in toAddresses)
            {
                message.To.Add(new MailAddress(mail));
            }
            SmtpClient.Send(message);
        }
        #endregion
    }
}
